package com.caishi.lkx.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.exam.mapper.WeekRankMapper;
import com.caishi.lkx.exam.model.WeekRankModel;
import com.caishi.lkx.exam.service.IWeekRankService;
import com.caishi.lkx.exam.vo.WeekRankVo;
import com.caishi.lkx.user.model.UserModel;
import com.caishi.lkx.user.service.IUserService;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.IBSMapper;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WeekRankServiceImpl implements IWeekRankService {

    @Resource
    private WeekRankMapper mapper;

    @Resource
    private IUserService<UserModel> userService;

    @Override
    public IBSMapper<WeekRankModel, Long> getMapper() {
        return mapper;
    }


    @Scheduled(cron = "0 0 0 ? * 1")
    public void cleanData() {
        // 每周一0点清空所有排行数据
        mapper.delete(wrappers());
    }

    @Override
    public IPage<WeekRankVo> getWeekRank(Page<WeekRankModel> page, Long categoryId) {
        var s = page(page, wrappers().eq(WeekRankModel::getCategoryId, categoryId).gt(WeekRankModel::getCount, 0).orderByDesc(WeekRankModel::getCount));
        var s1 = s.convert(v -> {
            var vo = new WeekRankVo();
            vo.setId(v.getUserId());
            vo.setCount(v.getCount());
            vo.setErrorCount(v.getErrorCount());
            return vo;
        });
        s1.setRecords(s1.getRecords().parallelStream().peek(v -> {
            var m = userService.userSimpleMsg(v.getId());
            BeanUtil.copyProperties(m, v);
        }).toList());
        return s1;
    }

    @Override
    public void addData(String userId, Long categoryId, int doCount, int errorCount) {
        if (mapper.update(null, Wrappers.<WeekRankModel>lambdaUpdate()
                .setSql(String.format(" count = count + %d,error_count = error_count + %d", doCount, errorCount))
                .eq(WeekRankModel::getUserId, userId)
                .eq(WeekRankModel::getCategoryId, categoryId)
        ) == 0) {
            var m = new WeekRankModel();
            m.setUserId(userId);
            m.setCategoryId(categoryId);
            m.setCount(doCount);
            m.setErrorCount(errorCount);
            insert(m);
        }
    }
}
